package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.service.SysUserOnlineBusService;
import com.andy.blog.common.constant.CacheConstants;
import com.andy.blog.common.core.domain.model.LoginUser;
import com.andy.blog.common.core.redis.RedisCache;
import com.andy.blog.common.page.PageUtilsDTO;
import com.andy.blog.dal.domain.SysUserOnlineDTO;
import com.andy.blog.dal.service.SysUserOnlineDalService;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * Created by andy on 2023/5/13 15:10
 */
@Service
public class SysUserOnlineBusServiceImpl implements SysUserOnlineBusService {

    @Resource
    private RedisCache redisCache;

    @Autowired
    private SysUserOnlineDalService userOnlineService;


    @Override
    public PageUtilsDTO<SysUserOnlineDTO> selectListByPage(String ipaddr, String userName) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnlineDTO> userOnlineList = Lists.newArrayList();
        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            } else if (StringUtils.isNotEmpty(userName) && Objects.nonNull(user.getUser())) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return PageUtilsDTO.build(new PageInfo<>(userOnlineList).getTotal(), userOnlineList);
    }

    @Override
    public void forceLogout(String tokenId) {
        redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
    }
}
